package com.codebo.homiematchbackend.manager;

import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class ChatWebSocketManager extends TextWebSocketHandler
{

    //    private static final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
    private static final List<WebSocketSession> sessions = new CopyOnWriteArrayList<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception
    {
        sessions.add(session);
        broadcast("系统消息: " + session.getId() + " 加入了聊天室");
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception
    {
        String payload = message.getPayload();
        broadcast(session.getId() + ": " + payload);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception
    {
        sessions.remove(session);
        broadcast("系统消息: " + session.getId() + " 离开了聊天室");
    }

    private void broadcast(String message)
    {
        for (WebSocketSession session : sessions)
        {
            try
            {
                session.sendMessage(new TextMessage(message));
            } catch (IOException e)
            {
                sessions.remove(session);
            }
        }
    }
}
